const orderFacade = require('../facade/order.server.facade.js');
const _ = require('lodash');
var ep = require('../util/event_proxy');

module.exports = {
    addOrder: addOrder,
    updateOrderStateByOrderId: updateOrderStateByOrderId,
    getAllOrderByCustomerId: getAllOrderByCustomerId,
    getOrderWithStateByMerchantId: getOrderWithStateByMerchantId
}


function addOrder(req, res, next) {

    let body = req.body;
    let order = body;

    orderFacade.addOrder(order, function addOrderCB(error, result) {

        if (error) {
            return next(error);
        }
        return ep.emit('success', res, result, "Add order Success!");

    });

}

function updateOrderStateByOrderId(req, res, next) {

    let params = req.params;
    let id = params.orderId;
    let state = params.state;


    if (_.isEmpty(id)) {
        return ep.emit('err', res, 422, "Order id is null");
    }

    if (_.isEmpty(state)) {
        return ep.emit('err', res, 422, "State is null");
    }

    orderFacade.updateOrderStateByOrderId(id, state, function updateOrderStateByOrderIdCB(error, result) {

        if (error) {
            return next(error);
        }

        orderFacade.getOrderByOrderId(id, function getOrderByOrderId(error, result) {

            if (error) {
                return next(error);
            }

            return ep.emit('success', res, result, "Update success");

        })


    });

}


function getAllOrderByCustomerId(req, res, next) {

    let params = req.params;
    let id = params.customerId;


    if (_.isEmpty(id)) {
        return ep.emit('err', res, 422, "Customer id is null");
    }

    orderFacade.getAllOrderByCustomerId(id, function getAllOrderByCustomerIdCB(error, result) {

        if (error) {
            return next(error);
        }


        return ep.emit('success', res, result, "Get success");

    });

}


function getOrderWithStateByMerchantId(req, res, next) {

    var merchant_id = req.session.merchant._id;

    let params = req.params;
    let state = params.state;


    if (_.isEmpty(state)) {
        return ep.emit('err', res, 422, "State id is null");
    }


    orderFacade.getOrderWithStateByMerchantId(merchant_id, state,function getOrderWithStateByMerchantIdCB(error, result) {

        if (error) {
            return next(error);
        }

        return ep.emit('success', res, result, "Get success");


    });

}
